package com.codeavatar.catools.plug.img;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestOptions;
import com.codeavatar.catools.R;
import com.codeavatar.catools.tool.CaCompressImageTool;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class GlidePlug {

    private static GlidePlug init = null;

    //实例化
    public synchronized static GlidePlug init() {
        if (null == init) {
            init = new GlidePlug();
        }
        return init;
    }

    public void downloadImage(Context context, String imgWebUrl, int width, int height,
                              DownloadImageCallback callback) {

        new Thread(() -> {
            Bitmap bitmap = null;
            try {
                bitmap = Glide.with(context).asBitmap().load(imgWebUrl).into(width, height).get();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (-1 != imgWebUrl.toLowerCase().indexOf(".jpg")) {
                callback.download(bitmap, Bitmap.CompressFormat.JPEG);
            } else {
                callback.download(bitmap, Bitmap.CompressFormat.PNG);
            }
        }).start();
    }

    public void downloadImage(Context context, String imgWebUrl, DownloadImageCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FutureTarget<File> futureTarget =
                        Glide.with(context).asFile().load(imgWebUrl).submit();
                try {
                    File file = futureTarget.get();
                    Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
                    if (-1 != imgWebUrl.toLowerCase().indexOf(".jpg")) {
                        callback.download(bitmap, Bitmap.CompressFormat.JPEG);
                    } else {
                        callback.download(bitmap, Bitmap.CompressFormat.PNG);
                    }
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Glide.with(context).clear(futureTarget);
            }
        }).start();
    }

    public void downloadImage(String imgWebUrl, DownloadImageCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 封装成网络地址
                    URL url = new URL(imgWebUrl);
                    // 打开一个连接
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    // 设置连接时长
                    httpURLConnection.setConnectTimeout(10 * 1000);
                    // 设置请求方式
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.connect();
                    //httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK
                    // 得到服务器返回过来的流对象
                    InputStream inputStream = httpURLConnection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    inputStream.close();
                    //压缩图片
                    bitmap = CaCompressImageTool.builder().compressScale(bitmap);
                    bitmap = CaCompressImageTool.builder().compressImage(bitmap, 10);

                    if (-1 != imgWebUrl.toLowerCase().indexOf(".jpg")) {
                        callback.download(bitmap, Bitmap.CompressFormat.JPEG);
                    } else {
                        callback.download(bitmap, Bitmap.CompressFormat.PNG);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void loadImg(Context context, String imgUrl, GlidePlaceHolderType type,
                        ImageView intoImg) {
        int placeHolderResId = this.getPlaceholderResId(type);
        Glide.with(context).load(imgUrl).placeholder(placeHolderResId).error(placeHolderResId).into(intoImg);
    }

    public void loadImg(Context context, String imgUrl, int placeHolderResId, ImageView intoImg) {
        Glide.with(context).load(imgUrl).placeholder(placeHolderResId).error(placeHolderResId).into(intoImg);
    }

    public void loadRoundedImg(Context context, String imgUrl, int radius,
                               GlidePlaceHolderType type,
                               ImageView intoImg) {
        int placeHolderResId = this.getPlaceholderResId(type);
        Glide.with(context).load(imgUrl).apply(new RequestOptions().transform(new CenterCrop(),
                new RoundedCorners(radius))).placeholder(placeHolderResId).error(placeHolderResId).into(intoImg);
    }

    public void loadRoundedImg(Context context, String imgUrl, int radius, int placeHolderResId,
                               ImageView intoImg) {
        Glide.with(context).load(imgUrl).apply(new RequestOptions().transform(new CenterCrop(),
                new RoundedCorners(radius))).placeholder(placeHolderResId).error(placeHolderResId).into(intoImg);
    }

    public enum GlidePlaceHolderType {
        Square, Rectangle, Circle, RectangleBanner, RectangleAd, RectangleGoodsThumbnail,
        CirclePortrait
    }

    //回调事件

    public interface DownloadImageCallback {
        void download(Bitmap bitmap, Bitmap.CompressFormat format);
    }

    public interface DownloadFileCallback {
        void download(File file);
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private int getPlaceholderResId(GlidePlaceHolderType type) {
        int resId = 0;
        switch (type) {
            case Square:
                resId = R.mipmap.ca_empty_square;
                break;
            case Rectangle:
                resId = R.mipmap.ca_empty_rectangle_banner;
                break;
            case Circle:
                resId = R.mipmap.ca_empty_square;
                break;
            case RectangleBanner:
                resId = R.mipmap.ca_empty_rectangle_banner;
                break;
            case RectangleAd:
                resId = R.mipmap.ca_empty_rectangle_banner;
                break;
            case RectangleGoodsThumbnail:
                resId = R.mipmap.ca_empty_rectangle_banner;
                break;
            case CirclePortrait:
                resId = R.mipmap.ca_empty_square;
                break;
        }
        return resId;
    }

}
